﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WhatCatch.Core2.Model;
using System.Linq;

namespace WhatCatch.Core2
{
    public class CrawlerClient
    {
        HandleConfig _config;
        //DataContainer _dataContainer;
        ICatchQueue _catchQueue;
        public CrawlerClient(HandleConfig config, ICatchQueue catchQueue)
        {
            _config = config;
            //_dataContainer = dataContainer;
            _catchQueue = catchQueue;
        }

        public void Run()
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();

            TaskFactory taskFactory = new TaskFactory();
            List<Task> taskList = new List<Task>();
            for (int i = 0; i < _config.HandleThreadNum; i++)
            {
                var task = taskFactory.StartNew((obj) =>
                  {
                      int index = (int)obj;
                      StartRobotThread(index);
                  }, i);
                taskList.Add(task);
            }

            ////等待所有结束
            //Task.WaitAll(taskList.ToArray());
            //sw.Stop();
            //Console.WriteLine("全部结束，耗时：" + sw.Elapsed.TotalSeconds);

            //var result = _dataContainer.GetAllDetails();
            //var rr = result.Select(p => p.Title).ToList();
            //int aa = 0;
        }

        private void StartRobotThread(int threadIndex)
        {
            CrawlerRobot robot = new CrawlerRobot(
                    new RobotInfo
                    {
                        RobotKey = "Robot" + threadIndex,
                        ThreadIndex = threadIndex
                    }, _catchQueue);

            int count = 0;
            while (true)
            {
                var result = robot.Handle();

                if (result == 0)
                    count++;
                else if (result == 1)
                    count = 0;

                Thread.Sleep(100);
            }
        }
    }
}
